package com.ywz.framework.mybatisplus;

import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.baomidou.dynamic.datasource.creator.DataSourceProperty;
import com.baomidou.dynamic.datasource.creator.DefaultDataSourceCreator;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.ywz.framework.mybatisplus.mapper.DatabaseMapper;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Objects;

/**
 * 类描述 -> 自定义动态数据源服务类
 *
 * @Author: ywz
 * @Date: 2024/11/17
 */
@Component
public class MyDynamicDataSourceService {
    @Value("${tenement.datasource.url-suffix}")
    private String urlSuffix;
    @Value("${tenement.datasource.username}")
    private String username;
    @Value("${tenement.datasource.password}")
    private String password;
    @Value("${tenement.datasource.driver-class-name}")
    private String driverClassName;
    @Value("${tenement.datasource.init-sql}")
    private String initSql;
    @Resource
    private DataSource dataSource;
    @Resource
    private DefaultDataSourceCreator dataSourceCreator;

    /**
     * 方法描述 -> 创建数据库并初始化表
     *
     * @param key 数据源标识
     * @param url 数据源URL
     * @Author: ywz
     * @Date: 2024/11/17
     */
    public void initTable(String key, String url) {
        // 配置数据源
        DataSourceProperty dataSourceProperty = new DataSourceProperty();
        dataSourceProperty.setLazy(true);
        dataSourceProperty.setUsername(username);
        dataSourceProperty.setPassword(password);
        if (!url.contains(":"))
            url = url + ":3306"; // 使用默认端口号
        dataSourceProperty.setUrl("jdbc:mysql://" + url);
        dataSourceProperty.setDriverClassName(driverClassName);
        // 创建sqlSessionFactory，配置mapper类
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.addMapper(DatabaseMapper.class);
        sqlSessionFactoryBean.setConfiguration(configuration);
        sqlSessionFactoryBean.setDataSource(dataSourceCreator.createDataSource(dataSourceProperty));
        try {
            // 获取sqlSession
            SqlSession sqlSession = Objects.requireNonNull(sqlSessionFactoryBean.getObject()).openSession();
            DatabaseMapper mapper = sqlSession.getMapper(DatabaseMapper.class);
            // 初始化数据库
            mapper.createDatabase("`saas-crm-" + key + "`");
            // 添加数据源到动态数据源
            DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
            dataSourceProperty.setUrl(dataSourceProperty.getUrl() + "/saas-crm-" + key + urlSuffix);
            DataSource dataSource1 = dataSourceCreator.createDataSource(dataSourceProperty);
            ds.addDataSource(key, dataSource1);
            // 初始化表
            ResourceDatabasePopulator popular = new ResourceDatabasePopulator();
            popular.addScript(new ClassPathResource(initSql));
            popular.execute(dataSource1);
            // 初始化管理员账户
            mapper.useDatabase("`saas-crm-" + key + "`");
            String adminAccount = key + "_admin";
            String adminPassword = "123456";
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            mapper.saveAdminAccount(adminAccount, passwordEncoder.encode(adminPassword));
            mapper.saveAdminRole();
            mapper.saveAdminUserRole();
            // 添加租户标签
            mapper.saveTenementLabel(key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
